package br.com.converter;


import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.bean.MessageBean;
import br.com.domain.Sexo;
import br.com.exception.ServiceException;
import br.com.service.SexoService;
import br.com.util.PropertiesUtil;
import br.com.util.SystemUtil;

@Named(value="sexoConverter")
@RequestScoped
public class SexoConverter implements Converter  {
	    
	    @Inject
	    SexoService sexoService;
     
	    @Override  
	    public Object getAsObject(FacesContext context, UIComponent component, String value)  {  
	    	 Sexo retorno = null;
	    	
	    	 if (value != null && value.trim().equals("")) {  
	             return retorno;  
	         } else {  
	             int id  = Integer.parseInt(value);  
	             try {
					retorno = (Sexo) sexoService.buscarPorId("Sexo", id);
				} catch (ServiceException e) {
					MessageBean.showAlertMessage
				     ("Sexo - " + PropertiesUtil.getMessageChave("msg-exception-converter-erro"));
				}
	         }  
	   
	         return retorno;  
	    }  
	  
	    @Override  
	    public String getAsString(FacesContext context, UIComponent component, Object value) {  
		   String retorno = ""; 
	    	try {
		    	
		    	if (value == null || value.equals("")) {  
		            return retorno;  
		        } else {
		        	
		        	if (value instanceof Sexo) {
		        		Sexo e = (Sexo) value; 
		        		
		        		if (SystemUtil.possuiDados(e.getId())) {
			        		retorno = ((Sexo) value).getId().toString();
			        	}
		        	}
		        } 
	        
	        } catch (Exception e) {
				MessageBean.showAlertMessage
				     ("Sexo - " + PropertiesUtil.getMessageChave("msg-exception-converter-erro"));
			}
	    	return retorno;
	    }
}
